<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Guild Members</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
            color: #333;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .container {
            width: 90%;
            max-width: 1200px;
            background: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 20px;
        }
        .member-list {
            display: flex;
            flex-wrap: wrap;
            gap: 20px;
            justify-content: center;
        }
        .member-card {
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            width: calc(25% - 20px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            text-align: center;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .member-card:hover {
            transform: scale(1.02);
        }
        .member-card img {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin-bottom: 10px;
            object-fit: cover;
        }
        .member-card h2 {
            font-size: 1.2em;
            margin: 0 0 5px;
            color: #555;
        }
        .member-card p {
            font-size: 0.9em;
            color: #777;
            margin: 0 0 10px;
        }
        .member-card .last-dynamic {
            font-size: 0.8em;
            color: #999;
        }
        .member-card.no-avatar {
            background: #f0f0f0; /* 灰色背景 */
        }
        .member-card.no-avatar img {
            border: 2px solid #ddd; /* 添加边框 */
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 80%;
            max-width: 600px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
        }
        .modal-title {
            font-size: 1.5em;
            color: #333;
        }
        .close {
            color: #aaa;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        .close:hover,
        .close:focus {
            color: black;
            text-decoration: none;
        }
        .modal-body {
            padding: 20px 0;
        }
        .modal-body p {
            margin: 10px 0;
            font-size: 1em;
            color: #555;
        }
        .modal-body h3 {
            font-size: 1.2em;
            color: #333;
            margin: 20px 0 10px;
        }
        .loading {
            text-align: center;
            font-size: 1.2em;
            color: #777;
        }
    </style>
</head>
<body>
<div class="container">
<!--    <h1>Guild Members</h1>-->
    <div class="member-list" id="memberList">
        <!-- Member cards will be inserted here by JavaScript -->
    </div>
</div>

<div id="myModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h2 class="modal-title">Member Details</h2>
            <span class="close">&times;</span>
        </div>
        <div class="modal-body">
            <p id="modalProfile">Profile: No profile</p>
            <p id="modalLastDynamic">Last Dynamic: No recent activity</p>
            <h3>Achievements</h3>
            <p id="modalAchievements">No achievements</p>
            <div class="loading" id="loadingMessage">Loading...</div>
        </div>
    </div>
</div>

<script>
    // 图片代理服务的URL
    const imageProxyUrl = 'https://res.cloudinary.com/your-cloud-name/image/fetch/';
    const defaultAvatar = '../assets/images/def-profile-gray.png'; // 默认头像

    // 辅助函数：回退到默认头像
    function fallbackToDefault(imgElement) {
        imgElement.src = defaultAvatar;
    }

    // Function to create member cards
    function createMemberCard(member) {
        const card = document.createElement('div');
        card.className = 'member-card';
        card.dataset.uuid = member.uuid; // 添加UUID到数据属性

        // 检查是否有头像
        if (!member.avatar) {
            card.classList.add('no-avatar'); // 添加无头像的样式
        }

        // Avatar
        const avatar = document.createElement('img');
        avatar.src = member.avatar ? imageProxyUrl + encodeURIComponent(member.avatar) : defaultAvatar;
        avatar.alt = 'Avatar';
        avatar.onerror = () => fallbackToDefault(avatar);
        card.appendChild(avatar);

        // Character Name
        const name = document.createElement('h2');
        name.textContent = member.character_name || 'N/A';
        card.appendChild(name);

        // Profile
        const profile = document.createElement('p');
        profile.textContent = member.profile || 'No profile';
        card.appendChild(profile);

        // Last Dynamic
        const lastDynamic = document.createElement('div');
        lastDynamic.className = 'last-dynamic';
        lastDynamic.textContent = member.last_dynamic || 'No recent activity';
        card.appendChild(lastDynamic);

        // 添加点击事件
        card.addEventListener('click', () => {
            showModal();
            fetchUserInfo(member.uuid);
        });

        return card;
    }

    // Function to fetch user info from the API
    async function fetchUserInfo(uuid) {
        try {
            const response = await fetch(`https://phantoms-backend.onrender.com/api/risingstones/user-info?uuid=${uuid}`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            displayUserInfo(data.data);
        } catch (error) {
            console.error('There has been a problem with your fetch operation:', error);
            displayError('Failed to load user information.');
        }
    }

    // Function to display user info in the modal
    function displayUserInfo(userInfo) {
        const modalTitle = document.querySelector('.modal-title');
        const modalProfile = document.getElementById('modalProfile');
        const modalLastDynamic = document.getElementById('modalLastDynamic');
        const modalAchievements = document.getElementById('modalAchievements');
        const loadingMessage = document.getElementById('loadingMessage');

        modalTitle.textContent = userInfo.character_name || 'N/A';
        modalProfile.textContent = `Profile: ${userInfo.profile || 'No profile'}`;
        modalLastDynamic.textContent = `Last Dynamic: ${userInfo.last_dynamic || 'No recent activity'}`;

        // Format achievements
        const achievements = userInfo.achieveInfo.map(achieve => {
            return `${achieve.achieve_name}: ${achieve.achieve_detail} (${achieve.achieve_time})`;
        }).join('<br>');
        modalAchievements.innerHTML = `Achievements: ${achievements || 'No achievements'}`;

        // Hide loading message
        loadingMessage.style.display = 'none';
    }

    // Function to display error message in the modal


    function displayError(message) {
        const modalTitle = document.querySelector('.modal-title');
        const loadingMessage = document.getElementById('loadingMessage');

        modalTitle.textContent = 'Error';
        loadingMessage.textContent = message;
        loadingMessage.style.display = 'block';
    }

    // Function to show the modal
    function showModal() {
        const modal = document.getElementById('myModal');
        modal.style.display = 'block';
    }

    // Function to hide the modal
    function hideModal() {
        const modal = document.getElementById('myModal');
        modal.style.display = 'none';
    }

    // Function to populate the member list
    function populateMemberList(data) {
        const memberList = document.getElementById('memberList');

        // Combine registered and unregistered members
        const allMembers = data.registered.concat(data.unRegister);

        allMembers.forEach(member => {
            const card = createMemberCard(member);
            memberList.appendChild(card);
        });
    }

    // Function to fetch data from the API
    async function fetchData() {
        try {
            const response = await fetch('https://phantoms-backend.onrender.com/api/risingstones/guild-member');
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const data = await response.json();
            populateMemberList(data.data);
        } catch (error) {
            console.error('There has been a problem with your fetch operation:', error);
        }
    }

    // Fetch data when the document is ready
    document.addEventListener('DOMContentLoaded', fetchData);

    // Get the modal
    const modal = document.getElementById('myModal');

    // Get the <span> element that closes the modal
    const span = document.getElementsByClassName('close')[0];

    // When the user clicks on <span> (x), close the modal
    span.onclick = hideModal;

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            hideModal();
        }
    };
</script>
</body>
</html>